home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C & C++ Multimedia Cyber Classroom
/
C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso
/
cpphtp2
/
code.jar
/
code
/
ch21
/
fig21_02.txt
< prev
next >
Wrap
Text File
|
1998-02-27
|
994b
|
40 lines
1 // Fig. 21.2: fig21_02.cpp
2 // Demonstrating the static_cast operator.
3 #include <iostream.h>
4
5 class BaseClass {
6 public:
7 void f( void ) const { cout << "BASE\n"; }
8 };
9
10 class DerivedClass: public BaseClass {
11 public:
12 void f( void ) const { cout << "DERIVED\n"; }
13 };
14
15 void test( BaseClass * );
16
17 int main()
18 {
19 // use static_cast for a conversion
20 double d = 8.22;
21 int x = static_cast< int >( d );
22
23 cout << "d is " << d << "\nx is " << x << endl;
24
25 BaseClass base; // instantiate base object
26 test( &base ); // call test
27
28 return 0;
29 }
30
31 void test( BaseClass *basePtr )
32 {
33 DerivedClass *derivedPtr;
34
35 // cast base class pointer into derived class pointer
36 derivedPtr = static_cast< DerivedClass * >( basePtr );
37 derivedPtr->f(); // invoke DerivedClass function f
38 }
39 }